package util

import (
	"bytes"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"encoding/binary"
	"fmt"
	"time"
)

func CreateClientAuthorization(appId string, secret string, data []byte) (string, error) {
	timestamp := time.Now().UnixMilli()
	bout := bytes.Buffer{}
	var err error
	err = binary.Write(&bout, binary.BigEndian, timestamp)
	if err != nil {
		return "", err
	}
	err = binary.Write(&bout, binary.BigEndian, []byte(appId))
	if err != nil {
		return "", err
	}
	err = binary.Write(&bout, binary.BigEndian, data)
	if err != nil {
		return "", err
	}
	s := hmacSha256(bout.Bytes(), secret)
	return fmt.Sprintf("%s;%d;%s;%s", "HmacSHA256", timestamp, appId, base64.URLEncoding.EncodeToString(s)), nil
}

func hmacSha256(b []byte, secret string) []byte {
	h := hmac.New(sha256.New, []byte(secret))
	h.Write(b)
	return h.Sum(nil)
}
